package com.hyh.admin.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyh.ad.common.core.domain.entity.SysLogininfor;
import com.hyh.admin.sys.mapper.SysLoginInforMapper;
import com.hyh.admin.sys.service.ISysLoginInforService;
import io.lettuce.core.RedisClient;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.redisson.api.RedissonClient;
@Service
public class SysLoginInforServiceImpl implements ISysLoginInforService {
    private static final Logger log = LoggerFactory.getLogger(SysLoginInforServiceImpl.class);
    @Autowired
    private SysLoginInforMapper sysLoginInforMapper;

    @Autowired
   private RedissonClient redissonClient;

    @Override
    public int insert(SysLogininfor sysLoginInfor) {
        return sysLoginInforMapper.insert(sysLoginInfor);
    }

    @Override
    public List<SysLogininfor> listAllSelect(SysLogininfor sysLoginInfor) {
        LambdaQueryWrapper<SysLogininfor> queryWrapper = new LambdaQueryWrapper<>(sysLoginInfor);
        queryWrapper.orderByDesc(SysLogininfor::getId);
        return sysLoginInforMapper.selectList(queryWrapper);
    }

    @Override
    public int delete(SysLogininfor sysLoginInfor) {
        return sysLoginInforMapper.deleteById(sysLoginInfor);
    }

    @Override
    public int deleteByIds(Long[] ids) {
        return sysLoginInforMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public SysLogininfor detail(SysLogininfor sysLoginInfor) {
        return sysLoginInforMapper.selectById(sysLoginInfor);
    }

    //分布式锁的实现
    public void test() throws InterruptedException {
        // 1. 获取锁
        RLock lock = redissonClient.getLock("lock");
        boolean flag = lock.tryLock(10, TimeUnit.SECONDS);
        // 2. 执行业务逻辑
       if (flag) {
           try {
               log.info("获取到锁");
               Thread.sleep(10000);
               System.out.println("获取锁成功" + Thread.currentThread().getName());
           } catch (Exception e) {
               throw new RuntimeException(e);
           } finally {
               // 3. 释放锁
               lock.unlock();
           }
       }
    }
}
